package com.orkasgb.framework.orkasgbframework.java.excel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson2.JSON;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.SheetUtil;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
public class ExcelUtils {

    /**
     * 导出Excel
     * <p> 使用方式如下：
     *     1、控制层定义
     *      @GetMapping("/exportLiquidMedicineArea")
     * 	    public void exportOEEPerformanceLoss(OEEPerformanceLossEntity oeePerformanceLoss, HttpServletResponse response) {
     * 		   log.info("调用exportOEEPerformanceLoss开始。");
     * 		   oeePerformanceLossService.exportOEEPerformanceLoss(oeePerformanceLoss, response);
     * 		   log.info("调用exportOEEPerformanceLoss结束.");
     *      }
     *
     *     2、前端如下定义导出方法即可：
     *     const exportLiquidMedicineArea =
     *     (liquidMedicineArea) =>
     *         window.open(`/api/liquidMedicineArea/exportLiquidMedicineArea?`
     *             + new URLSearchParams(liquidMedicineArea))
     * </p>
     *
     * @param dataList 数据结果集
     * @param fileName 文件名称
     * @param headerClass 表头类，需要使用@ExcelProperty注解相应的属性
     * @param response HttpServletResponse
     */
    public static void exportExcel(List<?> dataList, String fileName, Class<?> headerClass, HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            ExcelWriterBuilder excelWriter = EasyExcel.write(response.getOutputStream(), headerClass);
            excelWriter.sheet("sheet1").doWrite(dataList);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
